<?php

namespace Platform\Models\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Container\Container as App;
use Illuminate\Support\Facades\Redis;

/**
 * Trait PermissionTrait
 * @package Platform\Models\Traits
 * @property $id
 * @property $departments
 */
trait PermissionTrait{

    /**
     * @var App
     */
    private $app;

    /**
     * @var Model
     */
    protected $permission_model;


    /**
     * 获得权限模型
     * @return mixed
     */
    abstract function permission_model();

    /**
     * 创建模型对象
     * @return Model|mixed
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function makeModel() {

        $this->app = new App();
        $model = $this->app->make($this->permission_model());

        if (!$model instanceof Model){
            myResult()->stop(500,"Class {$this->permission_model()} must be an instance of Illuminate\\Database\\Eloquent\\Model");
        }

        return $this->permission_model = $model;
    }

    /**
     * 获取当用户的权限列表
     * @return array
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function allPermissions() {
        $permissions = [];
        if ($this->isAdmin()){
            foreach ($this->makeModel()->all() as $permission) {
                foreach ($permission->toPermissions() as $method => $uri) {
                    $permissions[$method][] = $uri;
                }
            }
        }else{
//            $role = $this->role;
            $department = $this->department;
            if ($department){
                foreach ($department->permissions as $permission) {
                    foreach ($permission->toPermissions() as $method => $uri) {
                        $permissions[$method][] = $uri;
                    }
                }
            }
        }

        return $permissions;
    }

    /**
     * 保存权限到缓存
     */
    public function savePermissions(){
        $permissions = $this->allPermissions();
        $key = 'permissions_'.$this->getTable().$this->id;
        Redis::set($key,serialize($permissions));
    }

    /**
     * 从缓存中获取权限
     * @return array
     */
    public function getPermissions(){
        $key = 'permissions_'.$this->getTable().$this->id;
        $permissions = unserialize(Redis::get($key));
        return $permissions;
    }

    /**
     * 清空当前用户权限缓存
     */
    public function delPermissions(){
        $key = 'permissions_'.$this->getTable().$this->id;
        Redis::del($key);
    }
}